﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ARchGL.Declaration.Platform.Service;
using ARchGL.Declaration.Platform.Service.Dtos;
using ARchGL.Declaration.Platform.Service.Dtos.Product;
using ARchGL.Declaration.Platform.Service.Dtos.Production;
using ARchGL.Declaration.Platform.Web.Models;
using TDF.Core.Ioc;
using TDF.Web.Attributes.Mvc;
using WebGrease.Css.Extensions;
using TDF.Data.EntityFramework.Repository;
using ARchGL.Declaration.Platform.Domain.Entities;
using TDF.Core.Exceptions;
using TDF.Core.Json;
using System.IO;
using System.Data;
using ARchGL.Declaration.Platform.Web.Common;
using TDF.Data.Repository;

namespace ARchGL.Declaration.Platform.Web.Controllers
{
    /// <summary>
    /// 库存管理
    /// </summary>
    public class ProductWarehouseController : AdminControllerBase
    {
        /// <summary>
        /// 区域
        /// </summary>
        protected readonly IBasicBusinessService BasicBusinessService;

        /// <summary>
        /// 生产服务
        /// </summary>
        protected readonly IProductionService ProductionService;

        /// <summary>
        /// 推车服务
        /// </summary>
        protected readonly ICarService CarService;

        /// <summary>
        /// 库存管理
        /// </summary>
        protected readonly IProductWarehouseService ProductWarehouseService;

        /// <summary>
        /// 库存管理
        /// </summary>
        protected readonly IMachineService MachineService;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="productionService"></param>
        /// <param name="productWarehouseService"></param>
        /// <param name="machineService"></param>
        /// <param name="carService"></param>
        /// <param name="basicBusinessService"></param>
        public ProductWarehouseController(IProductionService productionService, IProductWarehouseService productWarehouseService
            , IMachineService machineService, ICarService carService
            , IBasicBusinessService basicBusinessService)
        {
            ProductionService = productionService;
            ProductWarehouseService = productWarehouseService;
            MachineService = machineService;
            CarService = carService;
            BasicBusinessService = basicBusinessService;
        }

        public override ActionResult Index()
        {
            ViewBag.ProductTypeId = ProductionService.GetProductType(AreaId).Id;

            ////机位
            //ViewBag.MachineList = MachineService.GetPagedList(new MachineCriteria { AreaId = AreaId, PageIndex = 0, PageSize = 999 }).Rows;

            //推车
            var carList = CarService.GetSimpleCarPagedList(new CarCriteria { Status = CarStatus.Inbound }).Rows;
            ViewBag.CarList = carList;
            ViewBag.CarListJson = carList.ToJson();

            var productPropertys = ProductionService.GetProductPropertys(AreaId);

            return View(productPropertys);
        }

        [HttpGet]
        public ActionResult Log()
        {
            ViewBag.ProductId = Request.QueryString["pid"] ?? Guid.Empty.ToString();

            //产品
            var productTypeId = BasicBusinessService.GetProductTypeIdById(AreaId);
            ViewBag.ProductList = ProductionService.GetProductInfoBasePagedList(new ProductCriteria { ProductTypeId = productTypeId }).Rows;

            //机位
            ViewBag.MachineList = MachineService.GetPagedList(new MachineCriteria { AreaId = AreaId, PageIndex = 0, PageSize = 999 }).Rows;

            //推车
            ViewBag.CarList = CarService.GetCarPagedList(new CarCriteria { AreaId = AreaId, PageIndex = 0, PageSize = 999 }).Rows;

            return View();
        }

        /// <summary>
        /// 报废日志
        /// </summary>
        /// <returns></returns>
        public ActionResult ScrapLog()
        {
            return View();
        }

        /// <summary>
        /// 报废
        /// </summary>
        /// <returns></returns>
        public ActionResult Scrap()
        {
            //区域
            ViewBag.AreaList = BasicBusinessService.GetAreaList();

            //推车
            var carList = CarService.GetCarPagedList(new CarCriteria { AreaId = AreaId, Status = CarStatus.Inbound, PageIndex = 0, PageSize = 999 }).Rows;
            ViewBag.CarList = carList;
            ViewBag.CarListJson = carList.ToJson();

            //产品
            ViewBag.ProductListJson = GetProductList().ToJson();

            return View();
        }

        private List<ProductConfigInfoDto> GetProductList()
        {
            //作为页面JSON数据使用，为减少数据量，所以将这两个集合清除。
            var list = ProductionService.GetProductList();
            foreach (var item in list)
            {
                item.PropertyValues = null;
                item.PropertyDictionary = null;
            }

            return list;
        }

        #region 导入/导出 库存数据

        public ActionResult Export()
        {
            return View();
        }

        /// <summary>
        /// 导出库存信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult ExportExcel()
        {
            //获取导出数据
            var criteria = new WarehouseCarCriteria
            {
                Status = CarStatus.Inbound,
                PageIndex = 0,
                PageSize = 9999,
            };
            var list = ProductWarehouseService.GetCartsInWarehouse(criteria).Rows;
            if (list.Count == 0)
                return Json(new { success = false, errors = "没有数据！" }, JsonRequestBehavior.AllowGet);
            
            var dataTable = Utility.ListToDataTable(list);
            string path = Server.MapPath("~") + "\\Temporary\\Export\\";
            if (!Directory.Exists(path)) Directory.CreateDirectory(path);

            string fileName = "库存数据" + DateTime.Now.ToString("yyyy-MM-dd-HHmmss") + ".xls";
            string filepath = path + fileName;

            if (dataTable != null)//保存文件
            {
                NPOIHelper.Export(dataTable,  "库存数据", filepath);
                var fs = new FileStream(filepath, FileMode.OpenOrCreate);
                return File(fs, "application/vnd.ms-excel", fileName);
            }
            else
            {
                return Json(new { success = false, errors = "没有数据！" }, JsonRequestBehavior.AllowGet);
            }
        }

        [HttpPost]
        public ActionResult ImportExcel()
        {
            var file = Request.Files[0];

            if (Request.Files.Count == 0 || file.ContentLength == 0)
            {
                TempData["message"] = "请上传文件";
                return View("export");
            }

            if (file.ContentLength > 200000)
            {
                TempData["message"] = "文件超大";
                return View("export");
            }

            var path = Server.MapPath("~") + "\\Temporary\\Import\\";
            if (!Directory.Exists(path)) Directory.CreateDirectory(path);

            var fullPath = path + Guid.NewGuid() + ".xls";

            file.SaveAs(fullPath);

            var dt = ExcelHelper.ExcelToDataTable(fullPath, 0, 3, false);
            TempData["ImportData"] = dt;

            var messageList = CarService.Execute(dt, NPOIHelper.OperationList);

            TempData["message"] = messageList.Count > 0
                                ? string.Join("<br>", messageList)
                                : "更新完成";

            DeleteFile(Server.MapPath("~") + "\\Temporary\\Export\\" + file.FileName, fullPath);

            return View("export");
        }

        public ActionResult SyncProductWarehouse()
        {
            //获取导出数据       
            if (!ProductWarehouseService.SyncProductWarehouse())
            {
                throw new KnownException("更新失败，请稍后重试");
            }

            return Success();
        }

        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="downFile"></param>
        /// <param name="upFile"></param>
        private void DeleteFile(string downFile, string upFile)
        {
            try
            {
                if (System.IO.File.Exists(downFile))
                    System.IO.File.Delete(downFile);

                if (System.IO.File.Exists(upFile))
                    System.IO.File.Delete(upFile);

            }
            catch (Exception)
            {

            }
        }

        #endregion

        #region 模拟出入库

        /// <summary>
        /// 模拟入库
        /// </summary>
        /// <returns></returns>
        public ActionResult Op()
        {
            //区域
            ViewBag.AreaList = BasicBusinessService.GetAreaList();

            //产品
            ViewBag.ProductListJson = GetProductList().ToJson();

            //机位
            ViewBag.MachineListJson = MachineService.GetPagedList(new MachineCriteria { PageIndex = 0, PageSize = 999 }).Rows.ToJson();

            //推车
            var carList = CarService.GetCarBasePagedList(new CarCriteria()).Rows;
            ViewBag.CarList = carList;
            ViewBag.CarListJson = carList.ToJson();

            return View();
        }

        #region Ajax Action

        /// <summary>
        /// 模拟出入库
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SaveOp(SimulateModel model)
        {
            if (model.ProductCount <= 0)
            {
                throw new KnownException("产品数不正确");
            }

            string strCarKey;
            string[] CarKeyParts;
            string strProductCount;
            string[] ProductCountParts;

            if (Request.Params["CarKey[]"] != null)
            {
                strCarKey = Request.Params["CarKey[]"];
                CarKeyParts = strCarKey.Split(',');
                strProductCount = Request.Params["ProductCount[]"];
                ProductCountParts = strProductCount.Split(',');

                for (int i = 0; i < CarKeyParts.Length; i++)
                {
                    int iCarKey = model.CarKey;
                    int iProductCount = model.ProductCount;
                    int.TryParse(CarKeyParts[i], out iCarKey);
                    int.TryParse(ProductCountParts[i], out iProductCount);
                    if (model.Type == 1)
                    {//1入库
                        ProductWarehouseService.Inbound(model.AreaKey, model.MachineKey, 0, string.Empty, iCarKey, model.ProductKey, iProductCount);
                    }
                    else if (model.Type == 2)
                    {//2出库
                        ProductWarehouseService.Outbound(model.AreaKey, model.MachineKey, iCarKey);
                    }
                }
                return Success();
            }
            else
            {
                int iCarKey = model.CarKey;
                int iProductCount = model.ProductCount;
                if (model.Type == 1)
                {//1入库
                    ProductWarehouseService.Inbound(model.AreaKey, model.MachineKey, 0, string.Empty, iCarKey, model.ProductKey, iProductCount);
                }
                else if (model.Type == 2)
                {//2出库
                    ProductWarehouseService.Outbound(model.AreaKey, model.MachineKey, iCarKey);
                }
                return Success();
            }
        }

        #endregion

        #endregion

        #region Ajax Action

        /// <summary>
        /// 获取产品信息 - 分页数据集合
        /// </summary>
        /// <param name="criteria">筛选条件</param>
        /// <returns></returns>
        public ActionResult GetProductInfoPagedList(ProductCriteria criteria)
        {
            var list = ProductionService.GetProductInfoPagedList(criteria);

            return list.ToBootstrapTableModel();
        }

        /// <summary>
        /// 获取库存日志 - 分页数据集合
        /// </summary>
        /// <param name="criteria">筛选条件</param>
        /// <returns></returns>
        public ActionResult GetWarehouseRecordPagedList(WarehouseRecordCriteria criteria)
        {
            criteria.AreaId = AreaId;
            var list = ProductWarehouseService.GetWarehouseRecordPagedList(criteria);

            return list.ToBootstrapTableModel();
        }

        /// <summary>
        /// 获取报废日志 - 分页数据集合
        /// </summary>
        /// <param name="criteria">筛选条件</param>
        /// <returns></returns>
        public ActionResult GetScrapRecoredPagedList(ScrapRecoredCriteria criteria)
        {
            criteria.AreaId = AreaId;
            var list = ProductWarehouseService.GetScrapRecoredPagedList(criteria);

            return list.ToBootstrapTableModel();
        }

        /// <summary>
        /// 报废
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SaveScrap(ScrapRecoredModel model)
        {
            using (var repository = Ioc.Resolve<IRepositoryBase>().BeginTrans())
            {
                var car = repository.FindEntity<Car>(x => x.Number == model.CarNumber);
                car.CheckIsNullOrDeleted();

                ProductWarehouseService.AdjustProductCount(car.Key, model.ScrapType, model.ProductCount, repository);
            }

            return Success();
        }

        /// <summary>
        /// 库存调整（盘盈盘亏）
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult AdjustProductCount(WarehouseRecordAdjustDto model)
        {
            if (model.ProductCount < 0)
            {
                throw new KnownException("产品数不正确");
            }

            //if (model.CarCount < 0)
            //{
            //    throw new KnownException("车数不正确");
            //}

            ProductWarehouseService.AdjustProductCount(model);

            return Success();
        }

        #endregion
    }
}
